package db_main

import (
	"errors"
	"fmt"
	"log"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"

	"gorm.io/gorm"
)

func GetConfigPub() (*models_main.ConfigPub, error) {
	fName := "GetConfigPub"
	o := &models_main.ConfigPub{}
	err := global2.GetR().Order("id asc").
		Limit(1).
		Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetConfigPubSem() (*models_main.ConfigPub, error) {
	fName := "GetConfigPub"
	o := &models_main.ConfigPub{}
	err := global2.GetR().Table(o.ConfigPubSem()).Order("id asc").
		Limit(1).
		Find(o).Error
	log.Printf("%+v", o)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	global2.GetR().Model(&models_main.AppFace{}).Order("id asc").Find(&o.AppList)
	return o, err
}

func GetConfigPubSemWeb() (*models_main.ConfigPub, error) {
	fName := "GetConfigPub"
	o := &models_main.ConfigPub{}
	err := global2.GetR().Table(o.ConfigPubSemWeb()).Order("id asc").
		Limit(1).
		Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetConfigPubSpec() (*models_main.ConfigPub, error) {
	fName := "GetConfigPubSpec"
	o := &models_main.ConfigPub{}
	err := global2.GetR().Table(o.ConfigPubSpec()).Order("id asc").
		Limit(1).
		Find(o).Error
	log.Printf("%+v", o)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	global2.GetR().Model(&models_main.AppFace{}).Order("id asc").Find(&o.AppList)
	return o, err
}

func GetConfigPubJoycircle() (*models_main.ConfigPub, error) {
	fName := "GetConfigPubJoycircle"
	o := &models_main.ConfigPub{}
	err := global2.GetR().Table(o.ConfigPubJoycircle()).Order("id asc").
		Limit(1).
		Find(o).Error
	log.Printf("%+v", o)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	global2.GetR().Model(&models_main.AppFace{}).Order("id asc").Find(&o.AppList)
	return o, err
}

func GetConfigSource() ([]*models_main.ConfigPub, error) {
	fName := "GetConfigSource"
	var o []*models_main.ConfigPub
	err := global2.GetR().Table(models_main.ConfigPub{}.ConfigSource()).Order("id asc").
		Find(&o).Error
	log.Printf("%+v", o)
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	var appList []*models_main.AppFace
	global2.GetR().Model(&models_main.AppFace{}).Order("id asc").Find(&appList)
	for i, _ := range o {
		o[i].AppList = appList
	}
	return o, err
}
